<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>  - 完整游记</title>
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --accent-color: #e74c3c;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 1000px;
            margin: 0 auto;
            padding: 0;
            background-color: #f5f5f5;
        }

        /* 封面图片区域 */
        .cover-container {
            position: relative;
            height: 400px;
            overflow: hidden;
            border-radius: 0 0 8px 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .cover-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .cover-overlay {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 30px;
            background: linear-gradient(transparent, rgba(0,0,0,0.8));
            color: white;
        }

        .cover-title {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.5);
        }

        .cover-subtitle {
            font-size: 1.2em;
            margin-bottom: 20px;
            text-shadow: 0 1px 3px rgba(0,0,0,0.5);
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 20px;
        }

        .action-buttons {
            display: flex;
            gap: 15px;
            margin-top: 20px;
        }

        .action-btn {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 8px 15px;
            border: none;
            border-radius: 20px;
            background-color: rgba(255,255,255,0.2);
            color: white;
            cursor: pointer;
            transition: all 0.3s;
        }

        .action-btn:hover {
            background-color: rgba(255,255,255,0.3);
            transform: translateY(-2px);
        }

        .action-btn.active {
            background-color: var(--accent-color);
        }

        /* 作者信息区域 */
        .author-section {
            display: flex;
            align-items: center;
            padding: 20px;
            background-color: white;
            border-radius: 8px;
            margin: 20px 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .author-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 20px;
        }

        .author-info {
            flex: 1;
        }

        .author-name {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .author-bio {
            color: #666;
            font-size: 0.9em;
        }

        .follow-btn {
            padding: 8px 15px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
        }

        /* 内容区域 */
        .content-section {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        h2 {
            color: var(--secondary-color);
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 10px;
            margin-top: 0;
        }

        /* 精选图片展示 */
        .featured-gallery {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-top: 20px;
        }

        .featured-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 8px;
            transition: transform 0.3s;
            cursor: pointer;
            background-color: #f0f0f0; /* 添加背景色以便看到容器 */
        }

        .featured-image:hover {
            transform: scale(1.03);
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        }

        /* 打赏区域 */
        .reward-section {
            background: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            text-align: center;
        }

        .newand-options {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin: 15px 0;
            flex-wrap: wrap;
        }

        .newand-option {
            padding: 8px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .newand-option:hover, .newand-option.active {
            background: #1890ff;
            color: white;
            border-color: #1890ff;
        }

        .newand-btn {
            background: #ff4d4f;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s;
        }

        .newand-btn:hover {
            background: #ff7875;
        }

        #payment-modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .payment-modal-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            width: 300px;
        }

        #payment-encode {
            margin: 15px auto;
            width: 200px;
            height: 200px;
        }

        /* 评论区 */
        .comments-section {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .comment-count {
            font-size: 1.2em;
            margin-bottom: 20px;
            color: var(--secondary-color);
        }

        .comment-form {
            margin-bottom: 30px;
        }

        .comment-textarea {
            width: 100%;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            resize: vertical;
            min-height: 100px;
            margin-bottom: 10px;
        }

        .comment-textarea:focus {
            border-color: var(--primary-color);
            outline: none;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }

        .comment-submit {
            padding: 10px 20px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
        }

        .comment-submit:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }

        .comment-list {
            margin-top: 30px;
        }

        .comment-item {
            transition: all 0.3s;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 10px;
            background-color: #f9f9f9;
        }

        /* 添加以下样式到您的style部分 */
        .comment-item.hidden-comment {
            display: none;
        }

        .show-more-comments {
            text-align: center;
            margin-top: 15px;
        }

        #show-more-btn {
            background: none;
            border: none;
            color: var(--primary-color);
            cursor: pointer;
            padding: 8px 15px;
            border-radius: 20px;
            transition: all 0.3s;
        }

        #show-more-btn:hover {
            background-color: rgba(52, 152, 219, 0.1);
        }

        #show-more-btn i {
            margin-right: 5px;
            transition: transform 0.3s;
        }

        #show-more-btn.expanded i {
            transform: rotate(180deg);
        }

        /* 显示子评论按钮 */
        .child-comments-container {
            margin-left: 40px;
            border-left: 2px solid #eee;
            padding-left: 10px;
            background-color: #f9f9f9;
            border-radius: 4px;
            margin-top: 10px;
        }

        /* 子评论项样式 */
        .child-comment {
            background-color: #f0f0f0;
            border-radius: 4px;
            padding: 8px;
            margin: 5px 0;
        }

        /* 切换按钮样式 */
        .toggle-child-comments {
            color: var(--primary-color);
            cursor: pointer;
            font-size: 14px;
            margin-left: 10px;
            display: inline-block;
        }

        .toggle-child-comments:hover {
            text-decoration: underline;
        }

        .hidden-comment {
            display: none;
        }

        .comment-header {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .comment-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 10px;
        }

        .comment-author {
            font-weight: bold;
            margin-right: 10px;
        }

        .comment-date {
            color: #999;
            font-size: 0.8em;
        }

        .comment-content {
            line-height: 1.6;
        }

        .comment-actions {
            display: flex;
            gap: 15px;
            margin-top: 10px;
        }

        .comment-action {
            color: #666;
            font-size: 0.9em;
            cursor: pointer;
        }

        .comment-action:hover {
            color: var(--primary-color);
        }

        /* 返回按钮 */
        .back-button {
            display: inline-block;
            padding: 10px 20px;
            background-color: var(--primary-color);
            color: white;
            text-decoration: none;
            border-radius: 20px;
            margin: 20px 0;
            transition: all 0.3s;
        }

        .back-button:hover {
            background-color: #2980b9;
            transform: translateY(-2px);
        }
    </style>
    <!-- 添加这行 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">

    <script type="text/javascript" src="js/pay.js"></script>
    <script type="text/javascript" src="js/server.js"></script>
</head>
<body>
<!-- 封面图片区域 -->
<div class="cover-container">
    <img id="fmImg" src="" alt="" class="cover-image">
    <div class="cover-overlay">
        <h1 class="cover-title" id="nTitle"></h1>
        <div class="action-buttons">
            <button class="action-btn" id="like-btn">
                <i class="fas fa-heart"></i> <span id="likeAccount"></span>
            </button>
            <button class="action-btn" id="comment-btn">
                <i class="fas fa-comment"></i> <span id="commentCount"></span>
            </button>
            <button class="action-btn" id="favorite-btn">
                <i class="fas fa-bookmark"></i> <span id="favoriteCount"></span>
            </button>
        </div>
    </div>
</div>

<div class="container" style="padding: 20px;">
    <!-- 作者信息 -->
    <div class="author-section">
        <a href="/lv-user/myself2.html">
            <img id="uHead" src="" alt="作者头像" class="author-avatar">
        </a>
        <div class="author-info">
            <div id="uAccount" class="author-name"></div>
            <div id="uBio" class="author-bio"></div>
        </div>
        <button class="follow-btn">关注</button>
    </div>

    <!-- 文章内容 -->
    <div class="content-section">

    </div>

    <!-- 精选图片展示 -->
    <div class="content-section">
        <h2>精选图片</h2>
        <div class="featured-gallery">
            <img id="nImg1" src="" class="featured-image">
            <img id="nImg2" src="" class="featured-image">
            <img id="nImg3" src="" class="featured-image">
        </div>
    </div>

    <!-- 打赏区域 -->
    <div class="newand-section">
        <h3 class="newand-title">喜欢这篇游记吗？打赏支持作者吧！</h3>
        <p class="newand-desc">您的支持是作者创作更多优质内容的动力</p>
        <!-- 金额选择 -->
        <div class="newand-options">
            <div class="newand-option" data-amount="5">5元</div>
            <div class="newand-option" data-amount="10">10元</div>
            <div class="newand-option" data-amount="20">20元</div>
            <div class="newand-option" data-amount="50">50元</div>
            <div class="newand-option" id="custom-amount">自定义
                <input type="number" id="custom-input" min="1" max="1000" style="display:none;width:80px;margin-left:5px">
            </div>
        </div>
        <button class="newand-btn" id="reward-btn">立即打赏</button>
    </div>

    <!-- 支付弹窗 -->
    <div id="payment-modal" style="display:none;">
        <div class="payment-modal-content">
            <h3 id="payment-title">支付宝支付</h3>
            <p>支付金额：<span id="payment-amount">?0.00</span></p>
            <div id="payment-encode"></div>
            <p id="payment-tips">请使用支付宝APP扫描二维码完成支付</p>
            <button id="close-payment">关闭</button>
        </div>
    </div>

    <!-- 评论区 -->
    <div class="comments-section">
        <div class="comment-count">
            <i class="fas fa-comments"></i>
            <span class="comment-text">21条评论</span>
        </div>

        <div class="comment-form">
            <textarea class="comment-textarea" placeholder="写下你的评论..."></textarea>
            <button class="comment-submit">发表评论</button>
        </div>

        <div class="comment-list" id="comment-list">
            <!-- 评论将通过JS动态渲染 -->
        </div>

        <!-- 添加查看更多按钮 -->
        <div class="show-more-comments" id="show-more-comments" style="text-align: center; margin-top: 15px; display: none;">
            <button id="show-more-btn" style="background: none; border: none; color: var(--primary-color); cursor: pointer;">
                <i class="fas fa-chevron-down"></i> 查看更多评论
            </button>
        </div>
    </div>

    <a href="#" id="backButton" class="back-button">
        <i class="fas fa-arrow-left"></i> 返回列表
    </a>
</div>

<script>
    //全局函数
    function goBack() {
        console.log("返回按钮被点击");
        if (history.length > 1) {
            history.back();
        } else {
            window.location.href = '/index/index.html'; // 替换为您的实际列表页URL
        }
        return false;
    }

    document.addEventListener('DOMContentLoaded', function() {
        // 假设nid从URL参数获取
        const urlParams = new URLSearchParams(window.location.search);
        const nid = urlParams.get('nid') || window.nid;
        if (nid) {
            // 调用API获取帖子数据
            fetch(`/index/noteinfo?nid=${nid}`)
                .then(response => response.json())
                .then(data => {
                    try {
                        renderNote(data.data);
                        fetchComments(nid); // 确保在renderNote之后执行
                    } catch (e) {
                        console.error('渲染出错:', e);
                    }
                })
        }

        function renderNote(note) {
            try {// 渲染封面区域
                document.getElementById('nTitle').textContent = note.title;
                document.title = note.title + " - 完整游记"; // 新增这行修改标题
                if (note.img1) {
                    document.getElementById('fmImg').src = note.img1;
                }

                // 渲染作者信息（添加更严格的判断）
                const authorAvatar = document.getElementById('uHead');
                const authorName = document.getElementById('uAccount');
                const authorBio = document.getElementById('uBio');

                // 设置默认头像
                const defaultAvatar = note.gender === 'female' ? 'img/girl1.jpg' : 'img/boy1.jpg';

                // 处理头像
                authorAvatar.src = note.head || defaultAvatar;

                // 处理用户名和简介
                authorName.textContent = note.uname || '匿名用户';
                authorBio.textContent = note.bio || '这个人很懒，什么都没留下...';

                // 调试输出
                console.log('用户信息:', {
                    uname: note.uname,
                    head: note.head,
                    bio: note.bio
                });
                // 渲染帖子内容
                document.querySelector('.content-section').innerHTML =
                    `<h2>${note.title}</h2>
         <div>${note.content.replace(/\n/g, '<br>')}</div>`;

                // 渲染图片
                if (note.img1) document.getElementById('nImg1').src = note.img1;
                if (note.img2) document.getElementById('nImg2').src = note.img2;
                if (note.img3) document.getElementById('nImg3').src = note.img3;

                // 渲染统计数据 - 修正了ID匹配问题
                document.getElementById('likeAccount').textContent = formatCount(note.likeCount);
                document.getElementById('commentCount').textContent = formatCount(note.commentCount);
                document.getElementById('favoriteCount').textContent = formatCount(note.favoriteCount);

                // 存储到本地以便交互使用
                localStorage.setItem('noteData', JSON.stringify({
                    note: {
                        nid: note.nid,
                        uid: note.uid,
                        title: note.title,
                        content: note.content,
                        img1: note.img1,
                        img2: note.img2,
                        img3: note.img3,
                        createdAt: note.createdAt,
                        likeCount: note.likeCount,
                        favoriteCount: note.favoriteCount,
                        commentCount: note.commentCount
                    },
                    author: {
                        uid: note.uid,
                        uname: note.uname,
                        head: note.head,
                        zhanghao: note.zhanghao,
                        bio: note.bio,
                        gender: note.gender
                    }

                }));
            }catch (e){
                console.error('渲染出错:', e);
                document.querySelector('.content-section').innerHTML =
                    '<div class="error">内容加载失败，请刷新重试</div>';
            }
        }

        // 格式化数字显示 (1.2k 等形式)
        function formatCount(count) {
            if (!count) return '0';
            if (count >= 1000) {
                return (count / 1000).toFixed(1) + 'k';
            }
            return count.toString();
        }

        // 确保Font Awesome已加载
        if (!document.querySelector('link[href*="font-awesome"]')) {
            const faLink = document.createElement('link');
            faLink.rel = 'stylesheet';
            faLink.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css';
            document.head.appendChild(faLink);
        }

        // 点赞、收藏功能
        const likeBtn = document.getElementById('like-btn');
        const favoriteBtn = document.getElementById('favorite-btn');

        let isLiked = false;
        let isFavorited = false;

        likeBtn.addEventListener('click', function() {
            isLiked = !isLiked;
            const likeCount = document.getElementById('nlikeAcount');
            likeCount.textContent = formatCount(
                isLiked ? parseInt(likeCount.textContent) + 1 : parseInt(likeCount.textContent) - 1
            );
            likeBtn.classList.toggle('active', isLiked);

            // 这里应该添加API调用更新点赞状态
            // updateLikeStatus(nid, isLiked);
        });

        favoriteBtn.addEventListener('click', function() {
            isFavorited = !isFavorited;
            const favoriteCount = document.getElementById('nfavoriteCount');
            favoriteCount.textContent = formatCount(
                isFavorited ? parseInt(favoriteCount.textContent) + 1 : parseInt(favoriteCount.textContent) - 1
            );
            favoriteBtn.classList.toggle('active', isFavorited);

            // 这里应该添加API调用更新收藏状态
            // updateFavoriteStatus(nid, isFavorited);
        });

        // 图片点击事件
        document.querySelectorAll('.featured-image').forEach(img => {
            img.addEventListener('click', function() {
                if (this.src) {
                    window.open(this.src, '_blank');
                }
            });
        });
        // 打赏功能
        const options = document.querySelectorAll('.newand-option');
        const customOption = document.getElementById('custom-amount');
        const customInput = document.getElementById('custom-input');
        const rewardBtn = document.getElementById('reward-btn');
        const paymentModal = document.getElementById('payment-modal');
        const closePaymentBtn = document.getElementById('close-payment');

        let selectedAmount = 0;

        // 金额选择处理
        options.forEach(option => {
            option.addEventListener('click', function() {
                options.forEach(opt => opt.classList.remove('active'));

                if (this === customOption) {
                    this.classList.add('active');
                    customInput.style.display = 'inline-block';
                    customInput.focus();
                    selectedAmount = 0;
                } else {
                    this.classList.add('active');
                    selectedAmount = parseInt(this.dataset.amount);
                    customInput.style.display = 'none';
                }
            });
        });

        // 自定义金额处理
        customInput.addEventListener('input', function() {
            selectedAmount = parseInt(this.value) || 0;
            customOption.classList.toggle('active', selectedAmount > 0);
        });

        // 打赏按钮点击
        rewardBtn.addEventListener('click', async function() {
            if (selectedAmount <= 0) {
                alert('请选择打赏金额');
                return;
            }

            try {
                const response = await createPaymentOrder({
                    amount: selectedAmount,
                    subject: '文章打赏',
                    userId: 'uid' // 实际应用中替换为真实用户ID
                });

                showPaymentModal(response);
            } catch (error) {
                console.error('支付请求失败:', error);
                alert('支付请求失败: ' + error.message);
            }
        });

        // 关闭支付弹窗
        closePaymentBtn.addEventListener('click', function() {
            paymentModal.style.display = 'none';
            document.getElementById('payment-encode').innerHTML = '';
        });

        // 创建支付订单
        async function createPaymentOrder(data) {
            try{
                const controller = new AbortController();

                const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时

                const response = await fetch('/index/payment/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        outTradeNo: 'REWARD_' + Date.now(),
                        subject: data.subject,
                        totalAmount: data.amount.toFixed(2),
                        returnUrl: window.location.href // 添加回调URL
                    }),
                    timeout: 10000, // 设置超时时间
                });

                clearTimeout(timeoutId);

                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.data || '支付请求失败');
                }

                return await response.json();
            }catch (error) {
                if (error.name === 'AbortError') {
                    throw new Error('支付请求超时，请稍后');
                }
                throw error;
            }
        }

        // 显示支付弹窗
        function showPaymentModal(response) {
            document.getElementById('payment-amount').textContent = `￥${response.totalAmount}`;
            paymentModal.style.display = 'block';

            const encodeDiv = document.getElementById('payment-encode');
            encodeDiv.innerHTML = '';

            // 支付宝返回的是表单HTML，需要提交
            if (response.payForm) {
                const div = document.createElement('div');
                div.innerHTML = response.payForm;
                encodeDiv.appendChild(div);

                // 延迟提交表单，确保DOM已更新
                setTimeout(() => {
                    const form = document.querySelector('#payment-encode form');
                    if (form) {
                        form.submit();
                    } else {
                        console.error('未找到支付表单');
                    }
                }, 100);
            } else {
                console.error('未收到有效的支付表单');
            }
        }

        // 检查支付状态
        async function checkPaymentStatus(outTradeNo) {
            const interval = setInterval(async () => {
                try {
                    const response = await fetch(`/index/payment/status?outTradeNo=${outTradeNo}`);
                    const result = await response.json();

                    if (result.paid) {
                        clearInterval(interval);
                        alert('支付成功！感谢您的打赏！');
                        paymentModal.style.display = 'none';
                        document.getElementById('payment-encode').innerHTML = '';
                    }
                } catch (error) {
                    console.error('支付状态检查失败:', error);
                    clearInterval(interval);
                }
            }, 3000);
        }

        // 获取评论列表
        async function fetchComments(nid) {
            try {
                console.log(`正在获取nid=${nid}的评论...`)
                const response = await fetch(`/lv-index/comments/list/${nid}`, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                const result = await response.json();
                console.log('API返回结果:', result);

                if (result.code === 1) {
                    // 获取主评论
                    const comments = Array.isArray(result.data) ? result.data : [result.data];

                    // 为每个主评论获取子评论
                    for (const comment of comments) {
                        try {
                            const childResponse = await fetch(`/lv-index/childercomments/listUser?cid=${comment.cid}&nid=${nid}`);
                            if (childResponse.ok) {
                                const childResult = await childResponse.json();
                                console.log(`子评论结果 cid=${comment.cid}:`, childResult);
                                comment.childComments = (childResult.data && Array.isArray(childResult.data))
                                    ? childResult.data
                                    : [];
                            } else {
                                console.error(`获取子评论失败 cid=${comment.cid}:`, childResponse.status);
                                comment.childComments = [];
                            }
                        } catch (childError) {
                            console.error(`获取子评论出错 cid=${comment.cid}:`, childError);
                            comment.childComments = [];
                        }
                    }


                    renderComments(comments);
                    updateCommentCount(comments.length);
                } else {
                    console.error('获取评论失败:', result.msg);
                    renderComments([]);
                }
            } catch (error) {
                console.error('获取评论出错:', error);
                document.querySelector('.comment-list').innerHTML =
                    '<div class="error">评论加载失败，请刷新重试</div>';
            }
        }

        // 渲染评论列表
        function renderComments(comments) {
            const commentList = document.getElementById('comment-list');
            if (!commentList) return;

            commentList.innerHTML = comments?.length
                ? ''
                : '<div class="no-comments">暂无评论</div>';

            comments?.forEach((comment, index) => {
                const commentEl = createCommentElement(comment, index < 2);
                commentList.appendChild(commentEl);

                // 处理子评论
                if (comment.childComments && comment.childComments.length > 0) {
                    // 创建子评论容器
                    const childContainer = document.createElement('div');
                    childContainer.className = 'child-comments-container';
                    childContainer.style.display = 'none'; // 默认隐藏

                    // 添加子评论
                    comment.childComments.forEach(child => {
                        childContainer.appendChild(createCommentElement(child, true, true));
                    });

                    // 关键修改：确保插入到评论内容之后
                    const commentContent = commentEl.querySelector('.comment-content');
                    if (commentContent) {
                        commentEl.insertBefore(childContainer, commentContent.nextSibling);
                    } else {
                        commentEl.appendChild(childContainer);
                    }

                    // 添加切换按钮
                    const toggleBtn = document.createElement('span');
                    toggleBtn.className = 'toggle-child-comments';
                    toggleBtn.innerHTML = `<i class="fas fa-chevron-down"></i> 查看回复(${comment.childComments.length})`;

                    toggleBtn.addEventListener('click', function() {
                        const isHidden = childContainer.style.display === 'none';
                        childContainer.style.display = isHidden ? 'block' : 'none';
                        this.innerHTML = isHidden
                            ? `<i class="fas fa-chevron-up"></i> 收起回复`
                            : `<i class="fas fa-chevron-down"></i> 查看回复(${comment.childComments.length})`;
                    });

                    // 添加到操作区域
                    const actionsDiv = commentEl.querySelector('.comment-actions');
                    if (actionsDiv) {
                        actionsDiv.appendChild(toggleBtn);
                    }
                }
            });

            // 显示"查看更多"按钮
            const showMoreDiv = document.getElementById('show-more-comments');
            if (showMoreDiv) {
                const hiddenCount = document.querySelectorAll('.comment-item.hidden-comment').length;
                showMoreDiv.style.display = hiddenCount > 0 ? 'block' : 'none';
            }
        }

        // 创建评论元素的辅助函数
        function createCommentElement(comment, isVisible = true, isChild = false) {
            const commentElement = document.createElement('div');
            commentElement.className = `comment-item ${isChild ? 'child-comment' : ''} ${!isVisible ? 'hidden-comment' : ''}`;
            commentElement.dataset.cid = comment.cid;

            commentElement.innerHTML = `
        <div class="comment-header">
            <img src="${comment.head || 'img/boy1.png'}"
                alt="${comment.uname}"
                class="comment-avatar"
                onerror="this.src='img/girl1.png'">
            <div class="comment-author">${comment.uname || '匿名用户'}</div>
            <div class="comment-date">${formatDate(comment.creatAt)}</div>
        </div>
        <div class="comment-content">${comment.context}</div>
        <div class="comment-actions">
            <span class="comment-action like-comment" data-cid="${comment.cid}">
                <i class="fas fa-thumbs-up"></i> ${comment.likes || 0}
            </span>
            <span class="comment-action reply-comment" data-cid="${comment.cid}">
                <i class="fas fa-reply"></i> 回复
            </span>
        </div>
    `;

            return commentElement;
        }

        // 处理回复按钮点击事件
        document.addEventListener('click', function(e) {
            if (e.target.closest('.reply-comment')) {
                const replyBtn = e.target.closest('.reply-comment');
                const cid = replyBtn.dataset.cid;
                const commentItem = replyBtn.closest('.comment-item');

                // 移除现有的回复表单
                const existingForm = document.querySelector('.reply-form');
                if (existingForm) {
                    existingForm.remove();
                }

                // 创建回复表单
                const replyForm = document.createElement('div');
                replyForm.className = 'reply-form';
                replyForm.innerHTML = `
            <textarea class="reply-textarea" placeholder="回复${commentItem.querySelector('.comment-author').textContext}..."></textarea>
            <div class="reply-form-actions">
                <button class="cancel-reply">取消</button>
                <button class="submit-reply" data-cid="${cid}">回复</button>
            </div>
        `;

                // 插入到评论项下方
                commentItem.appendChild(replyForm);

                // 自动聚焦到文本区域
                replyForm.querySelector('.reply-textarea').focus();
            }

            // 处理取消回复
            if (e.target.closest('.cancel-reply')) {
                e.target.closest('.reply-form').remove();
            }

            // 处理提交回复
            if (e.target.closest('.submit-reply')) {
                const submitBtn = e.target.closest('.submit-reply');
                const cid = submitBtn.dataset.cid;
                const textarea = submitBtn.closest('.reply-form').querySelector('.reply-textarea');
                const replyText = textarea.value.trim();

                if (!replyText) {
                    alert('请输入回复内容');
                    return;
                }

                submitChildComment(cid, replyText);
            }
        });

        // 提交子评论的函数
        async function submitChildComment(cid, context) {
            const submitBtn = document.querySelector('.submit-reply');
            submitBtn.disabled = true;
            submitBtn.textContent = '提交中...';

            try {
                const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                if (!userInfo?.uid) {
                    alert("请先登录");
                    showLoginPrompt();
                    return;
                }

                const nid = new URLSearchParams(window.location.search).get('nid') || window.nid;
                const requestData = {
                    context: context,
                    cid: parseInt(cid),
                    nid: parseInt(nid),
                    uid: parseInt(userInfo.uid),
                    creatAt: new Date().toISOString()
                };

                console.log('提交数据:', requestData);

                const response = await fetch('/lv-index/childercomments/add', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                    body: JSON.stringify(requestData)
                });

                // 统一处理响应
                const responseText = await response.text();
                let result;

                try {
                    result = JSON.parse(responseText);
                } catch {
                    // 如果不是JSON，构造错误对象
                    throw new Error(responseText || `服务器错误 (${response.status})`);
                }

                if (!response.ok) {
                    throw new Error(result.msg || `请求失败 (${response.status})`);
                }

                // 成功处理
                document.querySelector('.reply-form')?.remove();

                // 关键修改：强制刷新评论列表
                await fetchComments(nid);

            } catch (error) {
                console.error('提交失败:', error);
                alert(`提交失败: ${error.message}`);
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = '回复';
            }
        }

        // 添加"查看更多评论"功能
        document.getElementById('show-more-btn')?.addEventListener('click', function() {
            const hiddenComments = document.querySelectorAll('.comment-item.hidden-comment');
            const showMoreBtn = this;

            if (hiddenComments.length > 0) {
                // 显示所有隐藏评论
                hiddenComments.forEach(comment => {
                    comment.classList.remove('hidden-comment');
                });

                // 更新按钮状态
                showMoreBtn.innerHTML = '<i class="fas fa-chevron-up"></i> 收起评论';
                showMoreBtn.classList.add('expanded');
            } else {
                // 隐藏超出初始数量的评论
                const allComments = document.querySelectorAll('.comment-item');
                const maxInitialComments = 2;

                allComments.forEach((comment, index) => {
                    if (index >= maxInitialComments) {
                        comment.classList.add('hidden-comment');
                    }
                });

                // 更新按钮状态
                showMoreBtn.innerHTML = '<i class="fas fa-chevron-down"></i> 查看更多评论';
                showMoreBtn.classList.remove('expanded');

                // 滚动到评论区域顶部
                document.querySelector('.comments-section').scrollIntoView({
                    behavior: 'smooth'
                });
            }
        });

        //日期格式
        function formatDate(dateString) {
            if (!dateString) return '刚刚';

            try {
                const now = new Date();
                const date = new Date(dateString);

                // 如果日期无效，返回原始字符串
                if (isNaN(date.getTime())) {
                    return dateString;
                }

                // 计算时间差（毫秒）
                const diff = now - date;
                const diffMinutes = Math.floor(diff / (1000 * 60));
                const diffHours = Math.floor(diff / (1000 * 60 * 60));
                const diffDays = Math.floor(diff / (1000 * 60 * 60 * 24));

                // 1分钟内显示"刚刚"
                if (diff < 60000) {
                    return '刚刚';
                }
                // 1小时内显示"**分钟前"
                else if (diff < 3600000) {
                    return `${diffMinutes}分钟前`;
                }
                // 24小时内显示"*小时前"
                else if (diff < 86400000) {
                    return `${diffHours}小时前`;
                }
                // 30天内显示"*天前"
                else if (diff < 2592000000) { // 30天
                    return `${diffDays}天前`;
                }
                // 超过30天显示具体年月日
                else {
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    return `${year}年${month}月${day}日`;
                }
            } catch (e) {
                console.error('日期格式化错误:', e);
                return dateString;
            }
        }

        // 更新评论数量
        function updateCommentCount(count) {
            const commentTextElement = document.querySelector('.comment-count .comment-text');
            if (commentTextElement) {
                commentTextElement.textContent = `${count}条评论`; // 只更新文本，不操作图标
            }

            // 同时更新封面区域的评论数
            const commentCountElement = document.getElementById('commentCount');
            if (commentCountElement) {
                commentCountElement.textContent = formatCount(count);
            }
        }

        //添加评论
        document.querySelector('.comment-submit').addEventListener('click',async function(){
            const submitBtn = this;
            submitBtn.disabled = true; //防止重复提交
            const originalText = submitBtn.textContent;
            submitBtn.textContent = '提交中...';

            const textarea = document.querySelector('.comment-textarea');
            const commentText = textarea.value.trim();

            if (!commentText){
                alert('请输入评论内容');
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
                return;
            }
            //获取文章id
            const urlParams = new URLSearchParams(window.location.search);
            const nid = urlParams.get('nid') || window.nid;

            if (!nid){
                console.error('无法获取文章内容');
                submitBtn.disabled = false;
                submitBtn.textContent = originalText;
                return;
            }
            try {
                // 检查用户信息
                const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                console.log('userInfo:', userInfo); // 确保 uid 存在且非空
                console.log('userInfo.uid:', userInfo.uid, typeof userInfo.uid); // 检查类型

                if (!userInfo || !userInfo.uid) {
                    alert("用户id缺失，请重新登录");
                    showLoginPrompt();
                    return;
                }

                const requestData = {
                    context: commentText,
                    nid: parseInt(nid),
                    uid: parseInt(userInfo.uid)
                };
                console.log('requestData:', requestData); // 确认 uid 在请求体中

                const response = await fetch('/lv-index/comments/add', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json;charset=UTF-8', // 明确指定charset
                        'Accept': 'application/json',
                    },
                    credentials: 'include',  // 确保发送cookie
                    body: JSON.stringify(requestData)
                });

                if (!response.ok){
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const result = await response.json();

                if (result.code === 1){
                    //清空输入框
                    textarea.value='';

                    //显示提交评论成功
                    alert('评论发布成功！');

                    //获取当前评论列表
                    const commentList = document.querySelector('.comment-list');
                    const noCommentsDiv = commentList.querySelector('.no-comments');

                    //如果有“暂无评论”提示，移除它
                    if (noCommentsDiv){
                        noCommentsDiv.remove();
                    }
                    //创建新评论元素并添加到列表顶部
                    const newComment = document.createElement('div');
                    newComment.className = 'comment-item';

                    newComment.innerHTML = `
                        <div class="comment-header">
                        <img src="${userInfo.head || 'img/boy1.png'}"
                            alt="${userInfo.uname || '匿名用户'}"
                            class="comment-avatar"
                            onerror="this.src='img/girl1.png'">
                        <div class="comment-author">${userInfo.uname || '匿名用户'}</div>
                        <div class="comment-date">刚刚</div>
                    </div>
                    <div class="comment-contet">${commentText}</div>
                    <div class="comment-actions">
                        <span class="comment-action like-comment" data-cid="new">
                            <i class="fas fa-thumbs-up"></i> 0
                        </span>
                        <span class="comment-action reply-comment" data-cid="new">
                            <i class="fas fa-reply"></i> 回复
                        </span>
                    </div>
                    `;
                    commentList.insertBefore(newComment,commentList.firstChild);

                    //更新评论计数
                    const countElement = document.querySelector('.comment-count');
                    if (countElement){
                        const currentCount = parseInt(countElement.textContent.match(/\d+/)[0]) || 0;
                        countElement.innerHTML = `i class="fas fa-comments"></i> ${currentCount + 1}条评论`;
                    }
                    // 替换原来的setTimeout调用
                    if (result.data?.cid !== 'new') {
                        // 只有当后端返回真实ID时才调用fetchComments
                        setTimeout(() => fetchComments(nid), 1000);
                    }
                }
            }catch (error){
                console.error('评论出错：', error);
            }
            //无论成功失败，按钮恢复提交状态
            submitBtn.disabled = false;
            submitBtn.textContent = originalText;
        });

        function showLoginPrompt() {
            const commentArea = document.querySelector('.comment-area');
            if (commentArea) {
                commentArea.innerHTML = `
            <div class="login-prompt">
                <p>请先登录后再评论</p>
                <a href="/lv-user/reg.html" class="login-btn">立即登录</a>
            </div>
        `;
            }
        }

        //添加回车提交评论功能
        document.querySelector('.comment-textarea').addEventListener('keydown',function (e){
            if (e.key === 'Enter' && !e.shiftKey){
                e.preventDefault();
                document.querySelector('.comment-submit').click();
            }
        });

        // 添加事件监听器方式
        document.getElementById('backButton').addEventListener('click', goBack);
    });

</script>
</body>
</html>
